package com.mediacloud.app.newsmodule.fragment.video.vod

import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.*
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.NetworkUtils
import com.eventTrack.TXReportManager
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.ListPreLoadKit
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool.preLoad2
import com.mediacloud.app.newsmodule.fragment.NotIntrestEvent
import com.mediacloud.app.newsmodule.fragment.video.x.RVListVideoKit
import com.mediacloud.app.newsmodule.utils.BindEventBus
import com.mediacloud.app.newsmodule.utils.CacheData
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.ExposurePoolService
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_video_seamless_layout.recyclerView
import kotlinx.android.synthetic.main.fragment_video_seamless_layout.refreshLayout
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class VideoSeamlessNewsListFragment : HqyNavFragment(),
    OnRefreshLoadMoreListener,ToolBarActionF5OrTop{


    var catalogID: String? = null
    private var pageSize = 20
    private var mRVListVideoKit: RVListVideoKit? = null
    private var preLoadKit: ListPreLoadKit<ArticleListData>? = null

    private var catalogItem: CatalogItem? = null

    private var recyclerAdapter: VideoSeamlessNewListAdapter? = null

    override fun getLayoutResID(): Int {
        return R.layout.fragment_video_seamless_layout
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
    }

    override fun initView() {
        navPaddingTopMatch()


        preLoadKit = object : ListPreLoadKit<ArticleListData>(requireContext(), refreshLayout) {
            override fun onSetData(data: ArticleListData) {
                setData(data)
            }

            override fun onPreload(preNum: Int) {
                preload(preNum)
            }

        }
        refreshLayout.setOnRefreshLoadMoreListener(this)
        refreshLayout.setEnableLoadMore(false)
        val itemAnimator = recyclerView.itemAnimator
        if (itemAnimator is SimpleItemAnimator) {
            itemAnimator.supportsChangeAnimations = false
        }
        mRVListVideoKit = RVListVideoKit(requireContext(), recyclerView, this)
        parentFragment?.let {
            if (it is SecondNav) {
                mRVListVideoKit?.playerView?.viewPlayer = it.viewPager
            }
        }
//        val manager = recyclerView.layoutManager as LinearLayoutManager
        recyclerView.setPadding(0, 0, 0, 0)
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var state = SCROLL_STATE_IDLE
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //性滑动的速度小于20我们就去区屏幕中可见的视频进行缓存
                if (state == SCROLL_STATE_SETTLING && abs(dy) < 20) {
                    checkPreLoad()
                }
                val lastVisibleItem =
                    (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                if (lastVisibleItem == (recyclerView.layoutManager as LinearLayoutManager).itemCount - 1) {
                    preLoadKit?.onLoadMore()
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    SCROLL_STATE_DRAGGING -> {
                        state = SCROLL_STATE_DRAGGING
                        checkPreLoad()
                    }
                    SCROLL_STATE_SETTLING -> {
                        state = SCROLL_STATE_SETTLING;
                    }
                    SCROLL_STATE_IDLE -> {
                        state = SCROLL_STATE_IDLE
                        app_jhapp_video_imp()
                    }
                    else -> {
                        state = SCROLL_STATE_IDLE
                    }
                }
            }

            private fun checkPreLoad() {
                val firstVisibleItem =
                    (recyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                val lastVisibleItem =
                    (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                try {
                    val articleList: MutableList<ArticleItem> = ArrayList()
                    for (i in firstVisibleItem..lastVisibleItem) {
                        articleList.add(recyclerAdapter!!.data[i])
                    }
                    preLoad2(requireContext(), articleList)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                if (NetworkUtils.isConnected()) {
                    showStateView(TYPE_LOADING, false)
                    onRefresh(refreshLayout)
                }
            }
        }
        showStateView(TYPE_LOADING, false)
//        val dataResult = this.readData("$catalogID", ArticleListData::class.java)
//        if (dataResult != null && dataResult.articleList.size > 0) {
//            showStateView(TYPE_LOADING, false)
//            setData(dataResult)
//        } else {
//            showStateView(TYPE_LOADING, false)
//            getDate()
//        }
        recyclerAdapter = VideoSeamlessNewListAdapter(requireContext())
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = recyclerAdapter

        BindEventBus(this, recyclerAdapter)


        getDate()
    }

    //private var pendingIndex = -1;
    override fun onLoadMore(refreshLayout: RefreshLayout) {
        Log.w(ListPreLoadKit.LTAG, "触发了 RefreshLayout onLoadMore")
        preLoadKit?.getMoreDate()
    }

    override fun unChosoed() {
        super.unChosoed()
        mRVListVideoKit?.stopPlay()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        preLoadKit?.onRefresh()
        mRVListVideoKit?.reset()
        getDate()
    }


    // var nextInfoFlowSmallAtLeft = true
    private fun getDate() {
        DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            preLoadKit?.hasMore = temp.more
            temp
        }.onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {}

                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun onNext(t: ArticleListData) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    preLoadKit?.preLoadData?.add(t)
                    if (preLoadKit!!.pageNum==1){
                        CacheData.saveData(requireContext(), catalogID!!, t.orginData.toString())
                    }

                    setData(t)
                    dataReady = true
                    if (hadChoosed) {
                        app_jhapp_video_imp()
                    }
                    preLoadKit?.preload()
                    try {
                        recyclerView.postDelayed({
                            if (userVisibleHint || !hidden) {
                                mRVListVideoKit?.let {
//                                    if (it.pendingStopTimeStamp == 0L) {//说明还没有切走
//
//
//                                    }
                                    try {
                                        mRVListVideoKit?.mDy = 1
                                        mRVListVideoKit?.initPendingPlay()
                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                                }

                            }

                        }, 1000)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh(false)
                    refreshLayout.finishLoadMore()

                    val t =
                        CacheData.readData(requireContext(), catalogID!!, ArticleListData::class.java)

                    if (t != null && t.articleList.isNotEmpty()) {
                        closeStateView()
                        setData(t)
                    } else {
                        if (recyclerAdapter?.data?.size == 0) {
                            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                        } else {
                            closeStateView()
                        }
                    }


                }

                override fun onComplete() {

                }
            })

    }


    private fun setData(t: ArticleListData) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed)
            return
        // ListPreLoadTool.preLoad2(requireContext(), t.articleList)
        if (preLoadKit!!.pageNum == 1) {
            val floatData = t.orginData.optJSONObject("data")
            if (FloatButtonGroup.haveFloatField(floatData)) {
                initFloatWin(floatData)
            } else {
                hideFloatWin()
            }
            recyclerAdapter?.data?.clear()
        }
        //组件必须
//        try {
//            addComponent(t.componentItems)
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
        val size: Int = recyclerAdapter?.itemCount!!
        recyclerAdapter?.data?.addAll(t.articleList)
        if (preLoadKit!!.pageNum == 1) {
            recyclerAdapter?.notifyDataSetChanged()
        } else {
            recyclerAdapter?.notifyItemRangeInserted(size, t.articleList.size)
        }
        if (recyclerAdapter?.data?.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
    }

    @SuppressLint("CheckResult")
    private fun preload(preNum: Int) {
        DataInvokeUtil.getContentList(catalogID, preNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ArticleListData) {
                    preLoadKit?.hasMore = t.more
                    preLoadKit?.onPreloadSuccess(t, preNum)
                }

                override fun onError(e: Throwable) {
                    preLoadKit?.onPreloadFail(preNum)
                }

                override fun onComplete() {

                }
            })
    }




    var hidden: Boolean = true;
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
        if (hidden) {
            mRVListVideoKit?.stopPlay()
        }
    }

//    override fun getLayoutResID(): Int {
//        return R.layout.fragment_info_flow
//    }

    override fun choosed() {
        super.choosed()
        recyclerView?.postDelayed({
            mRVListVideoKit?.pendingStopPlay = false
            mRVListVideoKit?.mDy = 1
            mRVListVideoKit?.initPendingPlay()
        }, 800)
        if (isAdded) {
            app_jhapp_video_imp()
        }

    }


    override fun onDestroy() {
        recyclerAdapter?.destroy()
        mRVListVideoKit?.onDestroy()
        super.onDestroy()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNotIntresting(event: NotIntrestEvent) {
        val list = recyclerAdapter?.data
        list?.let {
            for (i in it.indices) {
                if (it[i].id == event.id) {
                    list.remove(list[i])
                    recyclerAdapter?.notifyDataSetChanged()
                }
            }
        }

    }


    private var dataReady = false
    private val app_jhapp_video_impRunable: Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {
            try {
                val childCount = recyclerView.childCount
                for (i in 0 until childCount){
                    TXReportManager.getExposureArticles(recyclerView, recyclerAdapter?.data)
                        ?.forEach { obj ->
                            TXReportManager.getInstance().app_jhapp_video_imp(
                                catalogItem?.name,
                                obj,
                                i
                            )
                        }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun app_jhapp_video_imp() {
        if (!dataReady) return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        refreshLayout.setEnableRefresh(true)
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {

    }
}